Ext.namespace('SpeciesObservation');

SpeciesObservation.speciesManager = function(config) {

	this.unPrintedCard = {
			text: 'Generate Unprinted Cards'
		,	tooltip: 'Generate unprinted cards.'
		,	scope: this
		,	handler: this.generateUnprinted
	}

	this.speciesGrid = new SpeciesObservation.speciesGrid({
		border: false
	,	listeners: {
			scope: this
		,	rowdblclick :  function(grid,rowIndex,e){
				var l = this.refcardPan.getLayout();
				var rec = grid.getStore().getAt(rowIndex);
				this.refcardPan.record = rec;
				l.setActiveItem(1);
			}
		,	render: function(grid){
				grid.store.load({params:{start: 0, limit: 50}});
				grid.getColumnModel().getColumnById('stageid').hidden = false;
				grid.getColumnModel().getColumnById('publicId').hidden = false;
				grid.getColumnModel().getColumnById('cardId').hidden = false;
				grid.getColumnModel().getColumnById('lastModifiedId').hidden = false;
				grid.getView().getRowClass = function(record, index){
					if(record.data.stage=='Approved'){
						return 'green-row';
					}else if(record.data.stage=='Declined'){
						return 'red-row'
					}else {
						return ''
					}
				};
				grid.getSelectionModel().on("rowselect", function(sm, row, rec){
					this.getImage(rec.data);
				}, this);
				grid.getSelectionModel().on("rowdeselect", function(sm, row, rec){
					var path = [];
					this.panel.store.loadData(path);
					this.panel.refresh();
				}, this);
				grid.store.on("beforeload", function(a, b, c) {
					var path = [];
					this.panel.store.loadData(path);
					this.panel.refresh();
				}, this);
//				grid.getBottomToolbar().insert(13, this.unPrintedCard);
				grid.on("rowcontextmenu", function(grid, row, e){
					grid.showContextMenu(grid, row, e);
				}, this);
			}
		}
	});
	
	var speciesForm = new SpeciesObservation.speciesForm({
			border: false
		,	autoscroll: true	
		,	listeners: {
					scope: this
				,	render: function(form){
						form.refSave.text = 'Update Observation';
						form.refSave.on('click', function(){
							var l = this.refcardPan.getLayout();
							var msg = 'Updating observation...'
							var notice = "Observation Updated."	
							if(form.getForm().isValid()){
								var tAuth = form.find('name', 'auth');
								form.updateData(this.refcardPan.record.data.id, 'updateData', msg, notice, tAuth[0].getValue());
								this.refcardPan.refmyGrid.getStore().reload();
								l.setActiveItem(0);
							} else {
								SpeciesObservation.Notice.msg('Notice', 'Please enter required values.');			
							}							
						}, this);

						form.refCancel.on('click', function(){
							var l = this.refcardPan.getLayout();
							l.setActiveItem(0);
						}, this);
					}	
				,	show: function(form){
						form.getForm().setValues(this.refcardPan.record.data);
						form.refCancel.show();
					}
			}
	});

	var cardPan = new Ext.Panel({
			layout: 'card'
		,	region: 'north'
		,	ref: 'refcardPan'
		,	height: 250
		,	split: true
		,	title: '3x5 Observation Manager'
		,	activeItem: 0 
		,	record: ''
		,	border: false
		,	tools: [{
				id: 'help'
			,	scope: this
			,	qtip: 'View Help Documentation'
			,	handler: function(){
					window.open('http://code.google.com/p/species-observations/wiki/manager', '_blank');
				}
			}]
		,	tbar: [{
				text: 'Sign out'
			,	scope: this	
			,	handler: function(){
					Ext.Ajax.request({
							url: Config.baseUrl + 'resources/api/api.php'
						,	scope: this
						,	params: {
								cmd: 'signout'
							}
						,	success: function(r){
								var record = Ext.decode(r.responseText);
								window.location = Config.baseUrl + 'index.php'; 
							}
						,	failure: function(res){
								window.location = Config.baseUrl + 'index.php';
							}
					});
				}
			}, {
        	text: 'Expand Details'
        ,	enableToggle: true
        ,	toggleHandler: function(btn, state) {
						var grid = this.speciesGrid;
						if (state == true) {
							// Expand [+] nodes
							for(i=0; i<grid.store.data.length; i++) {
								grid.expander.expandRow(grid.view.getRow(i));
							}
						} else {
							// Collapse nodes
							for(i=0; i<grid.store.data.length; i++) {
								grid.expander.collapseRow(grid.view.getRow(i));
							}
						}
					}
				,	scope: this
        ,	pressed: false
	    }, '&nbsp;&nbsp;&nbsp;Card ID:', new Ext.ux.form.SearchField({
						store: this.speciesGrid.store
				 ,	width: 100
				 ,	paramName: 'occurrence_id'
			})]
		,	items: [this.speciesGrid, speciesForm]
	});
	
	var tpl = new Ext.XTemplate(
		'<tpl for=".">',
			'<div class="thumb-wrap">',
			'<div class="thumb noimageavail"><img src="{path}" onerror="this.alt=\'No Image Available.\'"></div>',
			'</div>',
		'</tpl>'
	);

	this.imgStore =  new Ext.data.ArrayStore({
			fields: ['path']
		,	data: []	
	});

	this.panel =  new Ext.DataView({
			region: 'center'
		,	store: this.imgStore
		,	style: 'background-color: white;'
		,	tpl: tpl
		,	emptyText: '<div class="noimageavail">No Image Available.</div>'
		,	listeners: {
				render: function(){
					this.refresh();
				}
			}
	});

	Ext.apply(this, config, {
			layout: 'border'
		,	defaults: {
					border: false
				,	autoScroll: true
			}
		,	items: [cardPan, this.panel]
	});

	SpeciesObservation.speciesManager.superclass.constructor.call(this, config);

};

Ext.extend(SpeciesObservation.speciesManager, Ext.Viewport, {

		getImage: function(rec){
			var arr = [];
			this.panel.refresh();
			if(!Ext.isEmpty(rec.filename)) arr.push([Config.s3BaseUrl + rec.path + rec.filename]);
			if(!Ext.isEmpty(rec.filename2)) arr.push([Config.s3BaseUrl + rec.path2 + rec.filename2]);
			if(!Ext.isEmpty(rec.filename3)) arr.push([Config.s3BaseUrl + rec.path3 + rec.filename3]);
			if(!Ext.isEmpty(rec.filename4)) arr.push([Config.s3BaseUrl + rec.path4 + rec.filename4]);
			if(!Ext.isEmpty(rec.filename5)) arr.push([Config.s3BaseUrl + rec.path5 + rec.filename5]);		
			this.panel.store.loadData(arr);
		}

	,	generateUnprinted: function(){
			if(!Ext.isEmpty(this.speciesGrid.getStore().data.items)){
				var d = Ext.get("download");
				if (!Ext.isEmpty(d)) {
					var params = { 
						cmd: 'generateUnprinted'				
					,	stage: 'Approved'
					,	printed: 0
					,	markedPrinted: 1
					}
					SpeciesObservation.Notice.msg('Success','Please wait...');
					d.dom.src = Config.baseUrl + 'resources/api/api.php?' + Ext.urlEncode(params);
				} else {
					SpeciesObservation.Notice.msg('Error','Error in exporting...');
				}
			} else {
				SpeciesObservation.Notice.msg('Notice','No Observations Available.');
			}
		}		

});